<template lang="pug">
  el-scrollbar(class="config-area-scrollbar" wrapClass="scrollbar-wrapper")
    .config-area
      el-form(v-if="globalConfigShow" labelWidth="80px" ref="initTemplateInfo" :model="initTemplateInfo" label-position="left")
        el-collapse(v-model="activeName")
          el-collapse-item(title="页面属性" name="页面属性")
            el-form(:model="commonPageConfig" ref="pageConfig" label-width="80px" label-position="left")
              el-form-item(label="类型" prop="formTypeId" :rules="{ required: true, message: '请选择', trigger: 'blur' }")
                el-select(ref="typeSelect" size="mini" v-model="commonPageConfig.formTypeId")
                  el-option(label="添加分类" value="添加分类")
                    el-button(type="text" icon="el-icon-plus" @click.native.stop="addOptionClick") 添加分类
                  el-option(v-for="one in formTypeList" :key="one.formTypeId" :value="one.formTypeId" :label="one.formTypeName")
              el-form-item(label="名称" prop="templateName" :rules="{ required: true, message: '请输入表单名称', trigger: 'blur' }")
                el-input(size="mini" v-model="commonPageConfig.templateName")
              el-form-item(label="描述" prop="descript")
                el-input(size="mini" v-model="commonPageConfig.descript")
              el-form-item(label="缩略图" prop="pageImg")
                el-upload(:show-file-list="false" :http-request="uploadRequest" :before-upload="beforeAvatarUpload" action="")
                  el-button(v-if="!pageImg" size="mini" type="primary") 上传图片
                  .page-img(v-if="pageImg")
                    img(:src="pageImg")
              //- el-form-item(label="表单参数")
              //-   el-button(type="primary" size="mini" @click="openParamsDialog") 参数配置
          el-collapse-item(title="全局样式" name="全局样式")
            el-form(:model="initTemplateInfo.globalCss" ref="globalCss" label-width="80px" label-position="left")
              el-form-item(label="页面宽度" prop="pageWidth")
                el-input(size="mini" type="number" v-model.number="initTemplateInfo.globalCss.pageWidth")
              el-form-item(label="主题自配" prop="customTheme" )
                el-checkbox.float-right(v-model="initTemplateInfo.globalCss.customTheme" )
              template(v-if="!initTemplateInfo.globalCss.customTheme")
                el-form-item(label="主题选择" prop="templateThemeId")
                  el-select(size="mini" v-model="initTemplateInfo.globalCss.templateThemeId")
                    el-option(v-for="item in templateThemeList" :label="item.label" :value="item.value")
              template(v-if="initTemplateInfo.globalCss.customTheme")
                el-form-item(label="背景色" prop="backgroundColor")
                  el-color-picker.float-right(v-model="initTemplateInfo.globalCss.backgroundColor" show-alpha)
                el-form-item(label="线框颜色" prop="borderColor")
                  el-color-picker.float-right(v-model="initTemplateInfo.globalCss.borderColor" show-alpha)
                el-form-item(label="字体颜色" prop="fontColor")
                  el-color-picker.float-right(v-model="initTemplateInfo.globalCss.fontColor" show-alpha)
                el-form-item(label="label宽度" prop="labelWidth")
                  el-input(size="mini" type="number" v-model.number="initTemplateInfo.globalCss.labelWidth")
                monaco-editor.mt-2(v-model="initTemplateInfo.globalCss.customStyle" :config="{label:'自定义样式',labelWidth:'90px',language:'css',position:'right'}")
          el-collapse-item(title="页面事件" name="页面事件")
            el-form(:model="initTemplateInfo.pageEvent" ref="pageEvent" label-width="80px" label-position="left")
              monaco-editor.mt-2(v-if="globalConfigShow" v-model="initTemplateInfo.pageEvent.created" :config="{label:'页面载入前',labelWidth:'90px',position:'right'}")
              monaco-editor.mt-2(v-if="globalConfigShow" v-model="initTemplateInfo.pageEvent.mounted"  :config="{label:'页面创建后',labelWidth:'90px',position:'right'}")
              monaco-editor.mt-2(v-if="globalConfigShow" v-model="initTemplateInfo.pageEvent.beforeDestroy"  :config="{label:'页面关闭时',labelWidth:'90px',position:'right'}")
      template(v-if="!globalConfigShow")
        el-button.global-btn(size="mini" type="primary" @click="showGlobalConfig") 全局
        json-form(ref="configComponent" :mounted="compontentMounted" :device="designDeviceChoose" :config="compontentInfo.configComponent" :value="compontentInfo.config" :cloneValue = "false" v-if="compontentInfo")
      el-dialog.page-img-dialog(:visible.sync="pageImgDialogVisible" width="700px" :close-on-click-modal="false" :append-to-body="true" :show-close="false")
        div.page-img-dialog-title
          span 缩略图
          svg-icon.shouqi-svg(icon-class="收起" @click.native="pageImgDialogVisible=false")
        img(:src="pageImg")
        el-row.text-center(slot="footer" class="dialog-footer")
          el-button(size="mini" @click="pageImgDialogVisible=false" type="primary") 关闭
    el-dialog(:visible.sync="addFormTypeVisible" title="添加分类" @close="closeAddTypeDialog" width="400px")
      el-form(:model="addTypeForm" ref="addTypeForm")
        el-form-item(prop="formTypeName")
          el-input(v-model="addTypeForm.formTypeName" placeholder="请输入表单类型" :rules="{required: true, max: 64, message: '新增类型不能为空且不大于64个字符', trigger: 'blur'}")
      span( slot="footer" class="dialog-footer")
        el-button( @click="addFormTypeVisible = false" size="mini") 取消
        el-button( @click="subAddTypeForm" size="mini" type="primary") 确定
    el-dialog(:visible.sync="setParamsDialog" title="表单参数配置" @close="setParamsDialogClosed" width="900px")
      div(class="mt-20 mb-20")
        tree-form-table(ref="treeFormTabel" :columns="columns" :data="paramsList" :selectChanged="selectChanged")
      span( slot="footer" class="dialog-footer")
        el-button( @click="setParamsDialog = false" size="mini") 取消
        el-button( @click="setParams" size="mini" type="primary") 确定
</template>

<script>
import _ from 'lodash'
import TreeFormTable from '@/components/TreeFormTable'
// import MonacoEditor from '../../../../common/components/MonacoEditor/MonacoEditor'
import MonacoEditor from '../../../../common/components/myForm/formElements/monacoEditor'
import jsonForm from '../../../../common/components/myForm/jsonForm'
import * as api from '../formPlugins/service'
import { getInterfaceListAll, getDictionaryTypeList } from '../formPlugins/service'
import { getToken } from '../../../../common/utils/auth'
export default {
  components: { MonacoEditor, jsonForm, TreeFormTable },
  props: ['initTemplateInfo', 'designDeviceChoose', 'commonPageConfig'],
  inject: ['designArea', 'operaTemplateRoot'],
  data() {
    return {
      pageImgDialogVisible: false,
      pageImg: '', // 缩略图
      interfaceList: [],
      dictionaryList: [],
      isTemplate: undefined,
      templateThemeList: [], // 主题数组
      globalConfigShow: true,
      activeName: ['全局样式', '页面属性', '页面事件', '组件配置', '组件事件'],
      compontentInfo: undefined, // 组件配置信息
      moduleListAll: [],// 业务模块
      addTypeForm: { formTypeName: null },
      addFormTypeVisible: false,
      formTypeList: [],
      paramsList: [],
      setParamsDialog: false,
      columns: [
        {
          label: '参数字段',
          type: 'treeInput',
          prop: 'key',
          width: '220px',
          require: true
        },
        {
          label: '别名',
          type: 'input',
          prop: 'templateName',
          width: '180px'
        },
        {
          label: '数据类型',
          type: 'select',
          options: [
            {
              value: 'string',
              label: '字符串'
            },
            {
              value: 'object',
              label: '对象'
            },
            {
              value: 'number',
              label: '数字'
            },
            {
              value: 'boolean',
              label: '布尔'
            },
            {
              value: 'integer',
              label: '整数'
            },
          ],
          prop: 'type',
          width: '140px'
        },
        {
          label: '是否数组',
          type: 'checkbox',
          prop: 'isArray',
          width: '80px',
        }
      ],
    }
  },
  methods: {
    selectChanged(type, value, item, isFirst) {
      // if (type == 'relationModelId') {
      //   let selectedObject = this.objList.find(one => one.value == value)
      //   if (selectedObject && selectedObject.modelFeature) {
      //     this.$set(item, 'disabledChildren', true)
      //     let objectPropertyList = this.$refs.treeFormTabel.fomatPropertyList(JSON.parse(selectedObject.modelFeature))
      //     if (isFirst == 'root') {
      //       this.tabelData = objectPropertyList
      //     } else {
      //       this.$set(item, 'property', objectPropertyList)
      //     }
      //   } else {
      //     this.$set(item, 'disabledChildren', false)
      //     if (isFirst == 'root') {
      //       this.tabelData = []
      //     } else {
      //       this.$set(item, 'property', [])
      //     }
      //   }
      // }
      if (type === 'type') {
        this.$set(item, 'relationModelId', null)
        if (value != 'object') {
          this.$set(item, 'hideAddChild', true)
        } else {
          this.$set(item, 'hideAddChild', false)
        }
        this.selectChanged('relationModelId', null, item, isFirst)
      }
    },
    setParams() {
      this.commonPageConfig.paramsList = _.cloneDeep(this.paramsList)
      this.setParamsDialog = false
    },
    setParamsDialogClosed() {
      this.paramsList = []
    },
    openParamsDialog() {
      this.setParamsDialog = true
      if (this.commonPageConfig.paramsList) {
        this.paramsList = _.cloneDeep(this.commonPageConfig.paramsList)
      }
      this.$nextTick(() => {
        this.$refs.treeFormTabel.setRootRow({
          key: 'params',
          templateName: '表单参数',
          type: 'object',
          disabledRow: true,
          isArray: false,
          hideAddChild: false
        })
      })
    },
    getFormTypeList() {
      api.getFormTypeItem().then(res => {
        if (res && res.data && res.data.rows) {
          this.formTypeList = res.data.rows
        } else {
          this.formTypeList = []
        }
      })
    },
    addOptionClick() {
      this.addFormTypeVisible = true
      this.$refs.typeSelect.blur()
      return false
    },
    subAddTypeForm() {
      this.$refs.addTypeForm.validate(valid => {
        if (valid) {
          api.setFormTypeItem(this.addTypeForm).then(res => {
            this.getFormTypeList()
            this.addFormTypeVisible = false
          })
        } else {
          return false
        }
      })
    },
    closeAddTypeDialog() {
      this.$refs.addTypeForm.resetFields()
    },
    // 上传缩略图
    uploadRequest(options) {
      let file = options.file
      let filename = options.filename
      let reader = new FileReader()


      if (file) {
        reader.readAsDataURL(file)
        reader.onload = () => {
          let base64Str = reader.result.split(',')[1]
          this.pageImg = reader.result
          this.commonPageConfig.pageImg = reader.result
        }
      }
    },
    beforeAvatarUpload(file) {
      const isImg = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg'
      const isLt1M = file.size / 1024 / 1024 < 1

      if (!isImg) {
        this.$message.error('上传图片格式不正确!')
      }
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过1M!')
      }

      return isImg && isLt1M
    },
    getAction() {
      return `${location.origin}/${process.env.VUE_APP_BPM_PREFIX}/bpm-base/file?token=${encodeURIComponent(getToken())}&X-token=${encodeURIComponent(getToken())}`
    },
    getImgUrl() {
      if (this.commonPageConfig.pageImg) {
        let url = this.commonPageConfig.pageImg.url
        this.pageImg = `${location.origin}/${process.env.VUE_APP_BPM_PREFIX + '/bpm-base' + url}&token=${encodeURIComponent(getToken())}&X-token=${encodeURIComponent(getToken())}`
      }
    },
    beforeAvatarUpload(file) {
      var lastFileName = file.name.split('.')[file.name.split('.').length - 1]
      var imgType = ['jpg', 'jpeg', 'png', 'gif']
      if (imgType.indexOf(lastFileName.toLowerCase()) < 0) {
        this.$message({
          message: '请选择图片上传',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleAvatarSuccess(response, file) {
      // if (!this.beforeAvatarUpload(file)) {
      //   return false
      // }
      // file.url = `/file?file=${encodeURIComponent(response)}`
      // this.commonPageConfig.pageImg = file
      // this.getImgUrl()
    },
    removeAvatar() {
      this.commonPageConfig.pageImg = undefined
      this.pageImg = ''
    },
    // 获得弹窗子页面
    compontentMounted(a, b, that) {
      const thatIsParent = () => {
        return this.initTemplateInfo.sortable[0].list.some(item => item.config.componentId === this.operaTemplateRoot.chooseComponentId)
      }
      that.$attrs.isParent = thatIsParent()

      let childPage = this.designArea().initTemplateInfo.sortable
      that.childPage = childPage
    },
    // 选中某个组件 展示他的配置
    compontentConfig(data) {
      this.compontentInfo = ''
      this.$nextTick(() => {
        this.compontentInfo = data
        this.operaTemplateRoot.chooseComponentId = this.compontentInfo.config.componentId
        this.activeName = ['全局样式', '页面属性', '页面事件', '组件配置', '组件事件']
        this.globalConfigShow = false
      })
    },
    // 切换到全局配置
    showGlobalConfig() {
      this.compontentInfo = undefined
      this.operaTemplateRoot.chooseComponentId = ''
      this.globalConfigShow = true
    }
  },
  created() {
    this.getFormTypeList()
    // 当前为模板应用才能有页面所用接口和字典
    // this.isTemplate = this.$store.state.application.isTemplate
    // console.log(this.$store.state.application)
    // getInterfaceListAll().then(data => {
    //   this.interfaceList = data
    // })
    // getDictionaryTypeList().then(data => {
    //   this.dictionaryList = data
    // })
    // api.getModuleListAll().then((data) => {
    //   this.moduleListAll = data
    // })
    this.$emit('update:initTemplateInfo', _.assign({
      // pageConfig: {
      //   templateName: '',
      //   descript: '',
      //   title: '',
      //   moduleId: '',
      //   iconSvg: '',
      //   interfaceIds: [],
      //   dictionaryIds: []
      // },
      globalCss: {
        pageWidth: '',
        customTheme: true,
        templateThemeId: '',
        backgroundColor: '',
        borderColor: '',
        fontColor: '',
        borderRadius: '',
        labelWidth: '',
        formWidth: '',
        customStyle: ''
      },
      pageEvent: {
        created: '',
        mounted: '',
        beforeDestroy: ''
      }
    }, this.initTemplateInfo))
    if (!this.initTemplateInfo.pageEvent.created || this.initTemplateInfo.pageEvent.created == '') {
      this.initTemplateInfo.pageEvent.created =
        `function () {
        //return $api.invokeInterface('接口名称', {page: 1})
        //.then(function(res) {
          // $data.name = res.name
        //})
      }`
    }
    if (!this.initTemplateInfo.pageEvent.mounted || this.initTemplateInfo.pageEvent.mounted == '') {
      this.initTemplateInfo.pageEvent.mounted =
        `function () {
        //return $api.invokeInterface('接口名称', {page: 1})
        //.then(function(res) {
          // $data.name = res.name
        //})
      }`
    }
    this.$emit('update:commonPageConfig', _.assign({
      templateName: '',
      descript: '',
      title: '',
      moduleId: '',
      pageImg: undefined,
      iconSvg: '',
      interfaceIds: [],
      dictionaryIds: []
    }, this.commonPageConfig))
    // this.getImgUrl()
  }

}
</script>
<style lang="scss" scoped>
.config-area {
  width: 100%;
  // width: 260px;
  min-height: 100%;
  box-sizing: border-box;
  border: 1px solid #ccc;
  position: relative;
  .global-btn {
    position: absolute;
    right: 50px;
    top: 7px;
  }
  // 缩略图
  .page-img {
    position: relative;
    width: 100px;
    height: 100px;
    // float: right;
    img {
      width: 100%;
      height: 100%;
      display: block;
      margin: auto;
    }
    .page-img-modal {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.4);
      z-index: 99;
      display: none;
      .el-icon-delete {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        width: 36px;
        height: 36px;
        display: inline-block;
        font-size: 36px;
        color: #fff;
        cursor: pointer;
      }
    }
    &:hover {
      .page-img-modal {
        display: block;
      }
    }
  }
}
</style>
<style lang="scss">
.config-area-scrollbar {
  width: 100%;
  height: 100%;
  .el-scrollbar__wrap {
    overflow-x: hidden !important;
  }
  .el-scrollbar__view {
    height: 100%;
  }
}
.config-area {
  .el-collapse-item__header {
    padding: 0 20px;
    background: #f5f7fa !important;
    color: #333 !important;
    font-weight: bold;
    font-size: 15px !important;
    height: 40px;
    box-sizing: border-box;
  }
  .el-collapse-item__wrap {
    border: none !important;
    .el-collapse-item__content {
      padding: 10px !important;
      border: none !important;
    }
  }
  .el-form-item {
    margin-bottom: 6px;
    input[type='number'] {
      width: 100% !important;
    }
    .el-select {
      width: 100% !important;
    }
    .el-form-item__error {
      padding-top: 0 !important;
    }
    .el-form-item__label {
      font-size: 13px !important;
      padding-right: 6px !important;
      text-align: left;
      &:before {
        content: '*' !important;
        color: #ef0000;
        opacity: 0;
        margin-right: 0px !important;
        display: inline-block;
        width: 10px;
      }
    }
  }
  .is-required {
    .el-form-item__label {
      font-size: 13px !important;
      &:before {
        opacity: 1;
      }
    }
  }
  .form-self-label {
    font-size: 13px;
    color: #666;
    &:before {
      content: '*' !important;
      color: #ef0000;
      opacity: 0;
      margin-right: 0px !important;
      display: inline-block;
      width: 10px;
    }
  }
  .form-self-label-required {
    &:before {
      opacity: 1 !important;
    }
  }
}

// 缩略图
.page-img-dialog {
  .el-dialog {
    .el-dialog__header {
      display: none;
    }
    .el-dialog__body {
      padding: 0 !important;
      .page-img-dialog-title {
        line-height: 50px;
        height: 50px;
        width: 100%;
        background: rgba(237, 239, 242, 1);
        border-radius: 4px 4px 0px 0px;
        color: #666666;
        padding: 0 10px;
        box-sizing: border-box;
        .shouqi-svg {
          cursor: pointer;
          font-size: 20px;
          color: #666;
          float: right;
          margin-top: 15px;
        }
      }
      img {
        width: 600px;
        height: auto;
        margin: 20px auto;
        display: block;
        outline: 1px solid #eee;
      }
    }
  }
}
.page-img-tooltip {
  .page-img-tip {
    padding: 4px 2px;
    cursor: pointer;
    &:hover {
      color: #2d77e6;
    }
  }
}
</style>
